package com.ls.x.android.services;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;

import com.ls.x.activity.beans.RemindItemBean;
import com.ls.x.service.ContextRemindModeService;
import com.ls.x.service.IContextRemindModeService;
import com.ls.x.tool.DatabaseHelper;

public class MainService extends Service {

	public static final int MSG_REGISTER_CLIENT = 1;
	public static final int MSG_UNREGISTER_CLIENT = 2;
	public static final int ADD_ONE_ALERT = 3;

	private IContextRemindModeService contextRemindModeService;
	private AlarmManager alarmManager;

	private Context context;

	private final Messenger mMessenger = new Messenger(new IncomingHandler());
	private ArrayList<Messenger> messengerClients = new ArrayList<Messenger>();

	@Override
	public void onCreate() {

		// send all alert that in database to AlarmManager on service on create
		context = getApplicationContext();
		alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

		DatabaseHelper databaseHelper = DatabaseHelper
				.getDBhelper(getApplicationContext());
		contextRemindModeService = new ContextRemindModeService(databaseHelper);

		List<RemindItemBean> remindItemBeanList = contextRemindModeService
				.getAllRemindItems();

		for (RemindItemBean remindItemBean : remindItemBeanList) {
			Intent intentForShowRemind = new Intent("com.ls.x.SHOW_REMIND");
			intentForShowRemind.putExtra("uuid", remindItemBean.getUuid());
			intentForShowRemind.putExtra("tital", remindItemBean
					.getContextBean().getTitle());
			intentForShowRemind.putExtra("summary", remindItemBean
					.getContextBean().getSummary());

			Date startDate = remindItemBean.getContextBean().getStartDate();

			int requestID = (int) System.currentTimeMillis();

			PendingIntent pendingIntent = PendingIntent
					.getBroadcast(context, requestID, intentForShowRemind,
							PendingIntent.FLAG_ONE_SHOT);

			alarmManager.set(AlarmManager.RTC_WAKEUP, startDate.getTime(),
					pendingIntent);
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mMessenger.getBinder();
	}

	/**
	 * Handler of incoming messages from clients.
	 */
	class IncomingHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_REGISTER_CLIENT:
				messengerClients.add(msg.replyTo);
				break;
			case MSG_UNREGISTER_CLIENT:
				messengerClients.remove(msg.replyTo);
				break;
			case ADD_ONE_ALERT:
				// msg.arg1
				break;
			default:
				super.handleMessage(msg);
			}
		}
	}

}
